const path = require('path');
const webpack = require('webpack');
const express = require('express');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

const ROOTPATH = process.cwd();
const CONFIGPATH = path.resolve(ROOTPATH, 'config');
const config = require(path.resolve(CONFIGPATH, 'webpack.dev.config.js'));

for (let key in config.entry) {
  const entry = config.entry[key];
  entry.unshift(path.resolve(CONFIGPATH, 'client.js'))
}

const app = express();
const compiler = webpack(config);
const devMiddleware = webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath,
  noInfo: true,
  stats: {
    colors: true
  }
});

const hotMiddleware = webpackHotMiddleware(compiler, {
  log: () => {
  }
});

compiler.hooks.compilation.tap('compilation', (compilation) => {
  compilation.hooks.htmlWebpackPluginAfterEmit.tapAsync(
    'compilation',
    (data, cb) => {
      hotMiddleware.publish({ action: 'reload' });
      cb()
    }
  )
})

app.use(devMiddleware);
app.use(hotMiddleware);

require('./api/students')(app);

app.listen('8080', function () {
  console.log('Server has started on localhost:8080');
})
